<template>
  <div class="stats-container">
    <!-- 筛选区域 -->
    <el-form :inline="true" :model="filter" class="filter-form">
      <el-form-item label="班级">
        <el-select v-model="filter.class" placeholder="请选择班级" style="width: 180px" clearable>
          <el-option
            v-for="item in classOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="评价项">
        <el-select v-model="filter.criteria" placeholder="请选择评价项" style="width: 180px" clearable>
          <el-option
            v-for="item in criteriaOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 图表控制和展示 -->
    <div class="chart-section">
      <div class="chart-controls">
        <el-radio-group v-model="chartType" @change="updateChart">
          <el-radio-button label="bar">柱状图</el-radio-button>
          <el-radio-button label="pie">饼图</el-radio-button>
        </el-radio-group>
      </div>
      <div class="chart-wrapper" ref="chartRef"></div>
    </div>

    <!-- 成绩列表 -->
    <el-table :data="scoreList" style="width: 100%" border>
      <el-table-column prop="studentId" label="学号" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="class" label="班级" />
      <el-table-column prop="score" label="分数" />
      <el-table-column prop="rank" label="排名" />
      <el-table-column prop="comment" label="评语" />
      <el-table-column prop="updateTime" label="更新时间" />
    </el-table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { useRouter } from 'vue-router'
import myAxios from '../../../plugins/myAxios'

const router = useRouter()
const chartRef = ref(null)
let chart = null

const filter = reactive({
  class: '',
  criteria: ''
})

const chartType = ref('bar')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

const classOptions = ref([])

const criteriaOptions = ref([])


const scoreList = ref([
  {
    studentId: '2021001',
    name: '张三',
    class: '计科2101',
    score: 85,
    rank: 15,
    comment: '表现良好，继续保持',
    updateTime: '2024-03-15 14:30'
  }
])

// 初始化图表
const initChart = () => {
  if (chart) {
    chart.dispose()
  }
  chart = echarts.init(chartRef.value)
  updateChart()
}

// 获取成绩统计数据
const getStatsData = async () => {
  try {
    const params = {
      class: filter.class,
      criteria: filter.criteria,
      semester: '',
      page: currentPage.value,
      pageSize: pageSize.value
    }
    const res = await myAxios.get('/admin/evaluation/stats', { params })
    scoreList.value = res.list
    total.value = res.total
    // 更新图表数据
    updateChart(res.distribution)
  } catch (error) {
    ElMessage.error('获取统计数据失败：' + error)
  }
}

// 更新图表数据
const updateChart = (distribution) => {
  const options = {
    title: { text: '成绩分布统计' },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: ['0-60', '60-70', '70-80', '80-90', '90-100']
    },
    yAxis: { type: 'value' },
    series: [{
      name: '人数',
      type: chartType.value,
      data: distribution || [2, 5, 15, 20, 8]
    }]
  }

  if (chartType.value === 'pie') {
    options.series[0].radius = '50%'
    options.series[0].data = options.xAxis.data.map((range, index) => ({
      name: range,
      value: options.series[0].data[index]
    }))
  }

  chart.setOption(options)
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  getStatsData()
}

const resetFilter = () => {
  filter.class = ''
  filter.criteria = ''
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getStatsData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getStatsData()
}

const getEvaluationNameList =async () => {
  const res = await myAxios.get('/admin/evaluation/getEvaluationNameList')
  criteriaOptions.value = res;
}

const getClassNameList = async () => {
  const res = await myAxios.get("/admin/grade/getOptions",{})
  let classNameList = res.classNameOptions;

  classOptions.value = classNameList.map(item => {
    let option = {};
    option.label = item;
    option.value = item;
    return option;
  })
}

// 监听路由参数变化
watch(() => router.currentRoute.value.query, (query) => {
  if (query.semester) {
    getStatsData()
  }
})

onMounted(() => {
  getEvaluationNameList();
  getClassNameList();
  initChart()
  getStatsData()
  window.addEventListener('resize', () => chart?.resize())
})

onUnmounted(() => {
  window.removeEventListener('resize', () => chart?.resize())
  chart?.dispose()
})
</script>

<style scoped>
.stats-container {
  width: 100%;
  padding: 20px;
}

.filter-form {
  margin-bottom: 20px;
}

.summary-cards {
  margin-bottom: 20px;
}

.card-content {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  color: #409EFF;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-controls {
  margin-bottom: 15px;
}

.chart-wrapper {
  width: 100%;
  height: 400px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

:deep(.echarts) {
  width: 100% !important;
  height: 100% !important;
}
</style>
